# Documentation Builder for Dragon Script.
# Copyright (C) 2009 Hajime Yoshimori <RoarLudros@gmail.com>
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# CJK Language LaTeX.
if(NOT PLATEX)
  set(PLATEX "platex")
endif(NOT PLATEX)

# European/American Language LaTeX.
if(NOT ELATEX)
  set(ELATEX "latex")
endif(NOT ELATEX)

# make index.
if(NOT MAKE_INDEX)
  set(MAKE_INDEX "mendex")
endif(NOT MAKE_INDEX)

# dvi pdf mx
if(NOT DVIPDFMX)
  set(DVIPDFMX "dvipdfmx")
endif(NOT DVIPDFMX)

# sty files checker
message(STATUS "Looking for kpsewhich")
if(NOT KPSEWHICH)
  find_program(KPSEWHICH NAMES kpsewhich)
endif(NOT KPSEWHICH)
if(NOT KPSEWHICH)
  message(STATUS "Looking for kpsewhich - not found")
  message(STATUS "TeX Building was canceled.")
  return()
endif(NOT KPSEWHICH)
message(STATUS "Looking for kpsewhich - ${KPSEWHICH}")

set(TARGET_NAMES "")

file(GLOB TEX_FILES "${CMAKE_CURRENT_SOURCE_DIR}/spec-*.tex")
foreach(TEX_FILE ${TEX_FILES})
  file(READ ${TEX_FILE} TEX_CONTENT)
  string(REGEX MATCHALL "\\\\usepackage{[^}]+}" TEX_PACKAGES ${TEX_CONTENT})
  foreach(TEX_USEPACKAGE ${TEX_PACKAGES})
	string(REGEX REPLACE "\\\\usepackage{([^}]+)}" "\\1" TEX_PACKAGE ${TEX_USEPACKAGE})
	string(REPLACE "," ";" TEX_PACKAGE ${TEX_PACKAGE})
	foreach(TEX_STY ${TEX_PACKAGE})
	  message(STATUS "Looking for TeX style ${TEX_STY}.sty")
	  execute_process(COMMAND ${KPSEWHICH} "${TEX_STY}.sty" "-progname=platex"
					  WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
					  RESULT_VARIABLE RET OUTPUT_QUIET ERROR_QUIET)
	  if(NOT RET)
		message(STATUS "Looking for TeX style ${TEX_STY}.sty - found")
	  else(NOT RET)
		message(STATUS "Looking for TeX style ${TEX_STY}.sty - not found")
		message(STATUS "TeX Building was canceled.")
		return()
	  endif(NOT RET)
	endforeach(TEX_STY)
  endforeach(TEX_USEPACKAGE)
  string(REGEX REPLACE "^.*(spec\\-[a-zA-Z_]+)\\.tex$" "\\1" BASE_NAME ${TEX_FILE})
  configure_file("${CMAKE_CURRENT_SOURCE_DIR}/build_tex.cmake.in"
				 "${CMAKE_CURRENT_BINARY_DIR}/${BASE_NAME}.cmake"
				 IMMEDIATE @ONLY)
  add_custom_target("${BASE_NAME}" ${CMAKE_COMMAND} 
					"-P" "${CMAKE_CURRENT_BINARY_DIR}/${BASE_NAME}.cmake"
					DEPENDS "${TEX_FILE}")
  set(TARGET_NAMES ${TARGET_NAMES} "${BASE_NAME}")
endforeach(TEX_FILE)

add_custom_target(texdoc)
add_dependencies(texdoc ${TARGET_NAMES})
